<template>
  <div>
    <div class="float-button" @click="openDrawer">
      <el-icon><Edit /></el-icon>
      <span>AI生成</span>
    </div>
    <el-drawer
      v-model="visible"
      title="AI生成商品信息"
      size="800px"
      :destroy-on-close="true"
    >
      <div class="drawer-content">
        <el-form :model="form" label-width="100px">
          <el-form-item label="商品名称">
            <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item label="商品描述">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="请输入商品描述"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="generateInfo" :loading="loading">
              生成商品信息
            </el-button>
          </el-form-item>
        </el-form>

        <div v-if="messages.length > 0" class="messages-container" ref="messagesContainer">
          <div v-for="(message, index) in messages" :key="index" class="message-item">
            <div class="message-role">{{ message.role === 'user' ? '用户' : 'AI助手' }}</div>
            <div class="message-content" v-html="message.content"></div>
          </div>
        </div>

        <div v-if="messages.length > 0" class="extract-action">
          <el-button type="success" @click="extractProductInfo">
            从对话中提取商品信息
          </el-button>
          <el-button type="primary" @click="applyGeneratedInfo">应用生成结果</el-button>
        </div>

        <div v-if="generatedInfo" class="generated-info">
          <h3>生成结果：</h3>
          <div class="info-item">
            <span class="label">商品名称：</span>
            <span>{{ generatedInfo.name }}</span>
          </div>
          <div class="info-item">
            <span class="label">商品简介：</span>
            <span>{{ generatedInfo.summary }}</span>
          </div>
          <div class="info-item">
            <span class="label">商品介绍：</span>
            <span v-html="generatedInfo.note"></span>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import {createAgentAi} from "@/uses/agentAi.js";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})
const name = defineModel('name')
const summary = defineModel('summary')
const note = defineModel('note')
const {ws,sendMessage,agentModel,connected,messages,loading}=createAgentAi()
const emit = defineEmits(['update:modelValue', 'apply'])
const visible = ref(false)
const form = ref({
  name: '',
  description: ''
})
const generatedInfo = ref(null)
const messagesContainer = ref(null)

// 监听消息变化，只保留滚动功能
watch(messages, (newMessages) => {
  if (newMessages && newMessages.length > 0) {
    nextTick(() => {
      scrollToBottom()
    })
  }
}, { deep: true })

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 提取商品信息
const extractProductInfo = () => {
  if (!messages.value || messages.value.length === 0) {
    ElMessage.warning('没有可提取的对话内容')
    return
  }

  try {
    // 获取最后一条AI助手的消息
    const lastAiMessage = [...messages.value].reverse().find(msg => msg.role === 'assistant')
    if (!lastAiMessage) {
      ElMessage.warning('未找到AI助手的回复内容')
      return
    }

    const content = lastAiMessage.content
    // 尝试从内容中提取JSON
    const jsonMatch = content.match(/\{[\s\S]*\}/)
    if (jsonMatch) {
      try {
        const productInfo = JSON.parse(jsonMatch[0])
        generatedInfo.value = {
          name: productInfo.name || form.value.name,
          summary: productInfo.summary || '',
          note: productInfo.note || ''
        }
        ElMessage.success('商品信息提取成功')
      } catch (parseError) {
        console.error('JSON解析失败:', parseError)
        ElMessage.error('商品信息格式错误')
      }
    } else {
      ElMessage.warning('未找到可提取的商品信息')
    }
  } catch (error) {
    console.error('提取商品信息失败:', error)
    ElMessage.error('提取商品信息失败')
  }
}

watch(() => props.modelValue, (val) => {
  visible.value = val
})

watch(() => visible.value, (val) => {
  emit('update:modelValue', val)
})

const generateInfo = async () => {
  if (!form.value.name || !form.value.description) {
    ElMessage.warning('请填写商品名称和描述')
    return
  }

  loading.value = true
  try {
    const prompt = `请根据以下信息生成商品详情，并以JSON格式返回：
商品名称：${form.value.name}
商品描述：${form.value.description}

请生成如下格式的JSON：
{
  "name": "优化后的商品名称",
  "summary": "100字以内的商品简介",
  "note": "商品详细介绍，包含产品特点、核心优势、使用场景等"
}

请确保生成的内容专业、吸引人，并且符合电商平台的要求。`

    sendMessage(prompt)
  } catch (error) {
    ElMessage.error('生成失败：' + error.message)
  } finally {
    loading.value = false
  }
}

const applyGeneratedInfo = () => {
  name.value=generatedInfo.value.name;
 summary.value=generatedInfo.value.summary;
  note.value=generatedInfo.value.note;
  visible.value = false
}

const openDrawer = () => {
  visible.value = true
}
</script>

<style scoped>
.drawer-content {
  padding: 24px;
  background-color: #f8f9fa;
  min-height: 100%;
}

.messages-container {
  margin: 24px 0;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  max-height: 400px;
  overflow-y: auto;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.message-item {
  margin-bottom: 20px;
  padding: 16px;
  border-radius: 8px;
  background-color: #f5f7fa;
  transition: all 0.3s ease;
}

.message-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.message-role {
  font-weight: 600;
  margin-bottom: 8px;
  color: #409EFF;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.message-role::before {
  content: '';
  display: inline-block;
  width: 8px;
  height: 8px;
  background-color: #409EFF;
  border-radius: 50%;
}

.message-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  color: #606266;
}

.extract-action {
  margin: 20px 0;
  text-align: center;
  display: flex;
  gap: 12px;
  justify-content: center;
}

.generated-info {
  margin-top: 24px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.generated-info h3 {
  color: #303133;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
}

.info-item {
  margin: 12px 0;
  padding: 8px 0;
  border-bottom: 1px dashed #e4e7ed;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-weight: 600;
  margin-right: 12px;
  color: #606266;
  min-width: 80px;
  display: inline-block;
}

.float-button {
  position: fixed;
  right: 30px;
  bottom: 120px;
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
  color: white;
  padding: 14px 24px;
  border-radius: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 10px;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 999;
  font-weight: 500;
}

.float-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
}

.float-button:active {
  transform: translateY(-1px);
}

.float-button .el-icon {
  font-size: 20px;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 20px 24px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #fff;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover),
:deep(.el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #409EFF inset;
}

:deep(.el-button) {
  padding: 12px 24px;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
  border: none;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}
</style>
